package blq.ssnb.eatandexercise;


import java.text.DecimalFormat;

import blq.ssnb.eatandexercise.step.StepCounterService;
import blq.ssnb.eatandexercise.step.StepDetector;
import blq.ssnb.eatandexercise.tool.MySharedPreferences;

import com.ant.liao.GifView;
import com.ant.liao.GifView.GifImageType;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

	private MySharedPreferences msp;
	private static String MTARGET ="target";//存放目标卡路里
	private static String MSTEPS="steps";
	private static String MNOWCAL="nowcal"; 
	private static String MSTATE="state";//存放状态 0：清除数据后关闭  1：启动状态中关闭 2:暂停状态中关闭
	private int state;

	private long time=0;//用于判断返回键是否两次
	private Context context;
	private int width;//屏幕的宽度
	private GifView gifview;//中间的gif动画

	private Button start,stop,shaoma,clear;
	private TextView Tv_target,Tv_nowcal,Tv_steps;
	private int steps=0;//记录歩数
	private float target=0,nowcal=0;//分别为目标卡路里和现在消耗的卡路里

	private Thread thread=null;
	private int step_length = 70;  //歩长 设定为70
	private int weight = 60;       //体重设置为60kg
	private float distance=0f; //走的米数


	Handler handler = new Handler(){
		@Override
		public void handleMessage(android.os.Message msg) {
			countDistance();     //调用距离方法，看一下走了多远
			nowcal = (float) (weight * distance * 0.001);	//得出消耗卡路里		
			countStep();//得到步数			
			upDateView();//更新ui
			if(nowcal-target>0){//如果大于预期
				Toast.makeText(context,R.string.exercise, Toast.LENGTH_LONG).show();
				Intent service = new Intent(MainActivity.this, StepCounterService.class);
				stopService(service);
				setStop();
				handler.removeCallbacks(thread);
			}
		};
	};



	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this ;
		msp=new MySharedPreferences(context, "pz");
		WindowManager wm = this.getWindowManager();
		width=wm.getDefaultDisplay().getWidth();
		if(thread==null){
			thread = new Thread(
					new Runnable() {

						@Override
						public void run() {
							int temp = 0;
							while (true) {
								try {
									Thread.sleep(100);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								if(StepCounterService.FLAG){
									Message msg = new Message();
									if (temp != StepDetector.CURRENT_SETP) {
										temp = StepDetector.CURRENT_SETP;
									}
									Log.e("run", "aaa");
									handler.sendMessage(msg);
								}
							}
						}
					});
			thread.start();
		}

		setView();
		setData();

	}
	private void setData() {
		gifview.setGifImageType(GifImageType.COVER);
		gifview.setGifImage(R.drawable.moving);
		gifview.setShowDimension(width/2, width/2);
		gifview.showCover();

		start.setOnClickListener(this);
		stop.setOnClickListener(this);
		shaoma.setOnClickListener(this);
		clear.setOnClickListener(this);

		stop.setAlpha(0.5f);
		clear.setAlpha(0.5f);
		state = msp.readClock(MSTATE);
		switch(state){
		case 0:
			break;

		case 1://启动状态中关闭
			target=msp.readFloat(MTARGET);
			setStart();
			nowcal = (float) (weight * distance * 0.001);
			countDistance();//走的米数
			countStep();//走的步数
			break;

		case 2:
			target=msp.readFloat(MTARGET);
			steps =msp.readInt(MSTEPS);
			nowcal = msp.readFloat(MNOWCAL);
			clear.setAlpha(1f);
			clear.setEnabled(true);
			break;
		default:
			break;
		}

		upDateView();
	}
	private void upDateView(){
		Tv_target.setText("Target Burn:"+formatDouble(target)+" Cal");
		Tv_nowcal.setText(formatDouble(nowcal)+" Cal");
		Tv_steps.setText(steps+" Steps");
	};
	private void setView() {
		gifview = (GifView)findViewById(R.id.main_gifview_heart);
		start=(Button)findViewById(R.id.main_bt_Start);
		stop=(Button)findViewById(R.id.main_bt_stop);
		shaoma=(Button)findViewById(R.id.main_bt_shaoma);
		clear=(Button)findViewById(R.id.main_bt_clear);		
		Tv_target=(TextView)findViewById(R.id.main_tv_target);
		Tv_nowcal=(TextView)findViewById(R.id.main_tv_nowcal);
		Tv_steps=(TextView)findViewById(R.id.main_tv_steps);

	}

	@Override
	public void onBackPressed() {
		if(time==0){
			time=System.currentTimeMillis();
			Log.e("tiem", time+"");
			Toast.makeText(context,R.string.fistbackpressed, Toast.LENGTH_SHORT).show();
			return;
		}else if((System.currentTimeMillis()-time)>3000){
			time=System.currentTimeMillis();
			Log.e("tiem", time+"");
			Toast.makeText(context,R.string.fistbackpressed, Toast.LENGTH_SHORT).show();
			return;
		}else{

			handler.removeCallbacks(thread);
			msp.save(MNOWCAL, nowcal);
			msp.save(MSTATE, state);
			msp.save(MSTEPS, state);
			msp.save(MTARGET, target);
			finish();
		}
	}
	@Override
	public void onClick(View view) {
		Intent service = new Intent(this, StepCounterService.class);
		switch (view.getId()) {
		case R.id.main_bt_Start:
			if(!StepCounterService.FLAG){//如果isrun =false 就是没有启动
				if(target==0){
					Toast.makeText(getApplicationContext(),R.string.Nocalories, 1).show();
					break;
				}
				if(nowcal-target>0){
					Toast.makeText(getApplicationContext(),R.string.ok, 1).show();
					break;
				}
				setStart();
				state=1;
				//启动服务跑计数
				startService(service);
			}
			break;
		case R.id.main_bt_stop:
			if(StepCounterService.FLAG){//isrun=true 表示已经启动了记数了
				setStop();
				//停止线程和服务
				state=2;
				stopService(service);
			}
			break;
		case R.id.main_bt_shaoma:
			//target=10;
			//Tv_target.setText("Target Burn:"+target+" Cal");
			startActivityForResult(new Intent(MainActivity.this,CaptureActivity.class), 2002);//启动二维码扫描
			break;
		case R.id.main_bt_clear:
			//擦除所有数据
			state=0;
			setClear();
			break;
		default:
			break;
		}

	}

	private  void setStart(){
		//启动的时候开始，扫码，清理按钮不能用，停止可用。且isrun 变为真
		start.setAlpha(0.5f);	
		start.setEnabled(false);
		shaoma.setAlpha(0.5f);
		shaoma.setEnabled(false);
		stop.setAlpha(1f);
		stop.setEnabled(true);
		clear.setAlpha(0.5f);
		clear.setEnabled(false);

		gifview.showAnimation();
	}
	private void setStop(){
		//停止的时候可以点开始，扫码，清理按钮。并且isrun变为false；

		start.setAlpha(1f);	
		start.setEnabled(true);
		shaoma.setAlpha(1f);
		shaoma.setEnabled(true);
		stop.setAlpha(0.5f);
		stop.setEnabled(false);
		clear.setAlpha(1f);
		clear.setEnabled(true);

		gifview.showCover();
	}
	private void setClear(){
		target=0f;
		nowcal=0f;
		distance=0f;
		steps=0;
		StepDetector.CURRENT_SETP = 0;
		upDateView();
		clear.setAlpha(0.5f);
		clear.setEnabled(false);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
				if(requestCode==2002&&resultCode==100){
					target+=data.getFloatExtra("calories", 0f);
					Tv_target.setText(formatDouble(target));
				}

	}

	private void countDistance() {
		if (StepDetector.CURRENT_SETP % 2 == 0) {
			distance = (float) ((StepDetector.CURRENT_SETP / 2) * 3 * step_length * 0.01);
		} else {
			distance = (float) (((StepDetector.CURRENT_SETP / 2) * 3 + 1) * step_length * 0.01);
		}
	}
	private void countStep() {
		if (StepDetector.CURRENT_SETP % 2 == 0) {
			steps = StepDetector.CURRENT_SETP;
		} else {
			steps = StepDetector.CURRENT_SETP +1;
		}
	}
	private String formatDouble(float doubles) {
		DecimalFormat format = new DecimalFormat("####.##");
		String distanceStr = format.format(doubles);
		return distanceStr.equals("0") ? "0.0": distanceStr;
	}

}
